﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using CDB.LinqModel.Data;
using CDB.LinqModel;
using CDB.LinqData;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.IO;

public partial class back_AddBuilders : System.Web.UI.Page
{
    #region Variable Declaration
    IDataRepository _dataObject = new DataRepository();
    Builder builder;
    State state;
    Country country;

    List<Country> countries = new List<Country>();
    List<State> states = new List<State>();
    List<City> cities = new List<City>();
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //bindCountry();
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                fillBuilder(Convert.ToString(Request.QueryString["Id"]));
        }
    }

    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        //bindStates();
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        //bindCities();
    }

    private void fillBuilder(string BuilderId)
    {
        builder = new Builder(_dataObject);
        builder.Id = Convert.ToInt16(BuilderId);
        builder.GetBuilderById();

        if (builder.Id != 0)
        {
            //bindCountry();
            txtName.Text = builder.Name;
            txtAddress.Text = builder.AddressLine;
            txtPhone.Text = builder.Phone;
            txtFax.Text = builder.Fax;
            txtEmail.Text = builder.Email;
            txtWebsite.Text = builder.Website;
            txtDescription.Text = builder.DescriptionLine;
            //txtPresenceIn.Text = builder.PresenceIn;
            //txtHeadQuarter.Text = builder.HeadQuarter;
            //txtOngoingProjects.Text = builder.OngoingProjects;
            //txtCompletedProjects.Text = builder.CompletedProjects;
            //ddlCountry.SelectedValue = builder.CountryId.ToString();
            //bindStatesByCountry(Convert.ToInt32(builder.CountryId));
            //ddlState.SelectedValue = builder.StateId.ToString();
            //bindCities();
            //ddlCity.SelectedValue = builder.CityId.ToString();
            ddlPropertyLocation.SelectedValue = builder.PropertyLocation;
            txtUsername.Text = builder.Username;
            txtUsername.Enabled = false;
            txtPassword.Attributes.Add("value", builder.Password);
            hfBuilderImageName.Value = builder.Image;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        
        

        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
        {
            builder = new Builder(_dataObject);
            builder.Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
            builder.GetBuilderById();

            builder.Name = txtName.Text;
            builder.AddressLine = txtAddress.Text;
            builder.Phone = txtPhone.Text;
            builder.Fax = txtFax.Text;
            builder.Email = txtEmail.Text;
            builder.Website = txtWebsite.Text;
            builder.DescriptionLine = txtDescription.Text;
            //builder.PresenceIn = txtPresenceIn.Text;
            //builder.HeadQuarter = txtHeadQuarter.Text;
            //builder.OngoingProjects = txtOngoingProjects.Text;
            //builder.CompletedProjects = txtCompletedProjects.Text;
            builder.Password = txtPassword.Text;
            builder.PropertyLocation = ddlPropertyLocation.SelectedItem.Value;
            //builder.CountryId = Convert.ToInt32(ddlCountry.SelectedValue);
            //builder.StateId = Convert.ToInt32(ddlState.SelectedValue);
            //builder.CityId = Convert.ToInt32(ddlCity.SelectedValue);
            //builder.IsActive = true;

            if (uplBuilderImage.HasFile)
                builder.Image = saveImage(uplBuilderImage);
            else
                builder.Image = hfBuilderImageName.Value;
            builder.Id = Convert.ToInt32(Request.QueryString["id"]);
            builder.DateUpdated = System.DateTime.Now;
            builder.Update();
            divMessage.InnerHtml = "<strong>Well done!</strong>&nbsp;Builder updated successfully!";
            divMessage.Attributes.Add("class", "alert alert-success");
            
        }
        else
        {

            if (checkIfUserNameExist(txtUsername.Text))
            {
                divMessage.InnerHtml = "<strong>Oh snap!</strong>&nbsp;Builder with this username already exists!";
                divMessage.Attributes.Add("class", "alert alert-error");
            }
            else
            {
                builder = new Builder(_dataObject);
                builder.Name = txtName.Text;
                builder.AddressLine = txtAddress.Text;
                builder.Phone = txtPhone.Text;
                builder.Fax = txtFax.Text;
                builder.Email = txtEmail.Text;
                builder.Website = txtWebsite.Text;
                builder.DescriptionLine = txtDescription.Text;
                //builder.PresenceIn = txtPresenceIn.Text;
                //builder.HeadQuarter = txtHeadQuarter.Text;
                //builder.OngoingProjects = txtOngoingProjects.Text;
                //builder.CompletedProjects = txtCompletedProjects.Text;
                builder.Username = txtUsername.Text;
                builder.Password = txtPassword.Text;
                builder.PropertyLocation = ddlPropertyLocation.SelectedItem.Value;
                //builder.CountryId = Convert.ToInt32(ddlCountry.SelectedValue);
                //builder.StateId = Convert.ToInt32(ddlState.SelectedValue);
                //builder.CityId = Convert.ToInt32(ddlCity.SelectedValue);
                //builder.IsActive = true;

                if (uplBuilderImage.HasFile)
                    builder.Image = saveImage(uplBuilderImage);
                else
                    builder.Image = hfBuilderImageName.Value;

                builder.DateCreated = System.DateTime.Now;
                builder.Create();
                clearControls();
                divMessage.InnerHtml = "<strong>Well done!</strong>&nbsp;Builder added successfully!";
                divMessage.Attributes.Add("class", "alert alert-success");
            }
        }
        

    }
    private string saveImage(FileUpload fuImage)
    {
        try
        {
            string filename = Path.GetFileName(fuImage.FileName);
            string[] fileArray = filename.Split('.');
            if (!Directory.Exists(Server.MapPath(ConfigurationManager.AppSettings["BuilderImagePath"].ToString())))
            {
                Directory.CreateDirectory(Server.MapPath(ConfigurationManager.AppSettings["BuilderImagePath"].ToString()));
            }

            fuImage.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["BuilderImagePath"].ToString() + filename));
            return (filename);
        }
        catch
        {
            return string.Empty;
        }
    }
    private bool checkIfUserNameExist(string userName)
    {
        Builder checkUser = new Builder(_dataObject);
        checkUser.Username = userName;
        checkUser.CheckBuilderByUsername();

        if (checkUser.Id != 0)
            return true;
        else
            return false;
    }
    private void clearControls()
    {
        txtName.Text = string.Empty;
        txtAddress.Text = string.Empty;
        txtPhone.Text = string.Empty;
        txtFax.Text = string.Empty;
        txtEmail.Text = string.Empty;
        txtWebsite.Text = string.Empty;
        txtDescription.Text = string.Empty;
        //txtPresenceIn.Text = string.Empty;
        //txtHeadQuarter.Text = string.Empty;
        //txtCompletedProjects.Text = string.Empty;
        //txtOngoingProjects.Text = string.Empty;
        txtUsername.Text = string.Empty;
        txtPassword.Text = string.Empty;
    }
    //private void bindCountry()
    //{
    //    country = new Country(_dataObject);
    //    countries = country.GetAllCountries();

    //    if (countries.Count > 0)
    //    {
    //        ddlCountry.DataSource = countries;
    //        ddlCountry.DataTextField = "Name";
    //        ddlCountry.DataValueField = "Id";
    //        ddlCountry.DataBind();
    //        ddlCountry.Items.Insert(0, "Select Country");
    //    }
    //}
    //private void bindStates()
    //{
    //    state = new State(_dataObject);
    //    states = state.GetAllStates();

    //    if (states.Count > 0)
    //    {
    //        ddlState.DataSource = states;
    //        ddlState.DataTextField = "Name";
    //        ddlState.DataValueField = "Id";
    //        ddlState.DataBind();
    //        ddlState.Items.Insert(0, "Select State");
    //    }
    //}
    //private void bindStatesByCountry(int countryId)
    //{
    //    state = new State(_dataObject);
    //    states = state.GetStatesByCountryId(countryId);

    //    if (states.Count > 0)
    //    {
    //        ddlState.DataSource = states;
    //        ddlState.DataTextField = "Name";
    //        ddlState.DataValueField = "Id";
    //        ddlState.DataBind();
    //        ddlState.Items.Insert(0, "Select State");
    //    }
    //}
    //private void bindCities()
    //{
    //    state = new State(_dataObject);
    //    cities = state.GetCitiesByStateId(Convert.ToInt32(ddlState.SelectedValue));
    //    if (cities.Count > 0)
    //    {
    //        ddlCity.DataSource = cities;
    //        ddlCity.DataTextField = "Name";
    //        ddlCity.DataValueField = "Id";
    //        ddlCity.DataBind();
    //        ddlCity.Items.Insert(0, "Select City");
    //    }

    //}
}